/**
 * 925. 长按键入
 * https://leetcode-cn.com/problems/long-pressed-name/
 */
public class Solutions_925 {
    public static void main(String[] args) {
//        String name = "alex", typed = "aaleex";  // output: true
//        String name = "saeed", typed = "ssaaedd";  // output: false
//        String name = "leelee", typed = "lleeelee";  // output: true
//        String name = "laiden", typed = "laiden";  // output: true
        String name = "vtkgn", typed = "vttkgnn";  // output: true
//        String name = "abcd", typed = "aaabbbcccddd";  // output: true
//        String name = "pyplrz", typed = "ppyypllr";  // output: false
//        String name = "alex", typed = "alexxr";  // output: false

        boolean result = isLongPressedName(name, typed);
        System.out.println(result);
    }

    public static boolean isLongPressedName(String name, String typed) {
        int len1 = name.length();
        int len2 = typed.length();
        if (len2 < len1) {
            // typed 长度不能小于 name
            return false;
        }
        if (len1 == len2) {
            // 长度相等时，直接 equals 判断
            return name.equals(typed);
        }
        char[] arr1 = name.toCharArray();
        char[] arr2 = typed.toCharArray();

        int idx1 = 0, idx2 = 0;
        while (idx1 < len1 && idx2 < len2) {
            if (arr1[idx1] == arr2[idx2]) {
                // 相同时
                idx1++;
                idx2++;
            } else if (idx2 > 0 && arr2[idx2] == arr2[idx2 - 1]) {
                // 多次键入的情况
                idx2++;
            } else {
                // 既不相同，也不是多次键入，即为键入错误的情况
                return false;
            }
        }
        // typed 还未遍历完成时，需要遍历检查剩余是字符是否是多次键入
        while (idx2 < len2) {
            if (idx2 > 0 && arr2[idx2] == arr2[idx2 - 1]) {
                // 多次键入的情况
                idx2++;
            } else {
                // 键入错误的情况
                return false;
            }
        }
        // 两个字符串都能够遍历完成，说明 typed 能够正确对应 name
        return idx1 == len1 && idx2 == len2;
    }
}
